/// [Pandigital prime](https://projecteuler.net/problem=41)
/// 9-digit pandigital divide by 3

fn main() {
    for i in (1..=9).rev() {
        let buff = vec![true; i];
        let (stat, prime) = recursion(0, &buff);
        if stat {
            println!("{:?}", prime);
        }
    }
}

fn recursion(n: usize, buff: &Vec<bool>) -> (bool, usize) {
    let nonzero = buff
        .iter()
        .enumerate()
        .filter(|(_, &x)| x)
        .map(|(i, _)| i)
        .collect::<Vec<_>>();
    if nonzero.len() == 0 {
        if is_prime(n) {
            (true, n)
        } else {
            (false, 0)
        }
    } else {
        for i in nonzero {
            let mut buff = buff.clone();
            buff[i] = false;
            let (stat, prime) = recursion(n * 10 + (buff.len() - i), &buff);
            if stat {
                return (stat, prime);
            }
        }
        (false, 0)
    }
}

fn is_prime(n: usize) -> bool {
    if n < 2 {
        return false;
    }
    for i in 2..n {
        if n % i == 0 {
            return false;
        }
        if i.pow(2) >= n {
            break;
        }
    }
    true
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn is_work() {
        assert!(!is_prime(1));
        assert!(is_prime(2));
        assert!(!is_prime(9));
        assert!(is_prime(2143));
    }
}
